package com.rongxun.hbwallet.ui.activities;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.rongxun.base.MvpActivity;
import com.rongxun.hbwallet.R;
import com.rongxun.hbwallet.constants.HttpConstants;
import com.rongxun.hbwallet.constants.IntentKey;
import com.rongxun.hbwallet.mvp.contract.ITransfer;
import com.rongxun.hbwallet.mvp.model.ApiModel;
import com.rongxun.hbwallet.mvp.presenter.TransferPresenter;
import com.rongxun.hbwallet.ui.adapter.ExcavateAdapter;
import com.rongxun.utils.ActivityUtils;
import com.rongxun.utils.EventUtil;
import com.rongxun.utils.FlyLog;
import com.rongxun.utils.Md5Utils;
import com.rongxun.utils.StatusBarUtil;
import com.rongxun.utils.ToastUtils;
import com.rongxun.utils.wallet.ETHWallet;
import com.rongxun.utils.wallet.VerifyMnemonicWordTag;
import com.rongxun.view.InputPwdDialog;
import com.rongxun.widget.LoadingDialog;

import org.web3j.utils.Convert;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建者     庄丰泽
 * 创建时间   2018/8/22 13:47
 * 描述	      购买矿机
 */

public class ExcavateActivity extends MvpActivity<ITransfer.IView, TransferPresenter> implements ITransfer.IView, SeekBar.OnSeekBarChangeListener, InputPwdDialog.OnInputDialogButtonClickListener {


    @BindView(R.id.toolbar_title)
    TextView     mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar      mToolbar;
    @BindView(R.id.et_transfer_address)
    EditText     mTransferAddress;
    @BindView(R.id.et_receipt_address)
    EditText     mReceiptAddress;
    @BindView(R.id.excavate_tv_title)
    TextView     mExcavateTvTitle;
    @BindView(R.id.excavate_rv)
    RecyclerView mRv;
    @BindView(R.id.excavate_tv_profit)
    TextView     mProfit;
    @BindView(R.id.seekbar)
    SeekBar      seekbar;
    @BindView(R.id.tv_gas_cost)
    TextView     tvGasCost;
    @BindView(R.id.btn_next)
    Button       mBtnNext;
    @BindView(R.id.toolbar_back)
    ImageView    mToolbarBack;

    private Dialog loadingDialog;

    private InputPwdDialog    inputPwdDialog;
    private BottomSheetDialog mBottomSheet;

    private ETHWallet     mEthWallet;
    private String        mPwd;
    private DecimalFormat mFormater;
    private String        mEtherUnit;

    private static final double miner_min = 0.00002520;
    private BigInteger realGas;
    private BigDecimal gaslimit = new BigDecimal("21000");
    private BigInteger mBalance = new BigInteger("0");

    String money="0";
    private List<VerifyMnemonicWordTag> mMCitys;

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void showLoading(boolean show) {
        if (show)
            loadingDialog.show();
        else
            loadingDialog.cancel();
    }


    @Override
    public void showError(String msg, String errorCode) {

    }

    @Override
    public void checkPermissionsSuccessful(String... permissions) {

    }

    @Override
    public void release() {
        EventUtil.unregister(this);
        if (inputPwdDialog != null)
            inputPwdDialog.cancel();

        if (mBottomSheet != null)
            mBottomSheet.cancel();
    }

    @NonNull
    @Override
    public TransferPresenter createPresenter() {
        return new TransferPresenter(this, new ApiModel(this));
    }


    @Override
    public void showEthBalance(BigInteger ethBalance) {

    }

    @Override
    public void showCityBalance(BigInteger cityBalance) {
        mBalance = cityBalance;
    }

    @Override
    public void showTransferResult(String txHash) {
        ActivityUtils.startActivityWithAnimotion(this,
                new Intent(this, TransferResultActivity.class)
                        .putExtra(IntentKey.ETCTRANSFER_TYPE, TransferResultActivity.TRANSFER_ACCOUNTS)
                        .putExtra(IntentKey.TRANSFER_ADDRESS, mTransferAddress.getText().toString())
                        .putExtra(IntentKey.TRANSFER_MONEY, money)
                        .putExtra(IntentKey.GASCOST, tvGasCost.getText().toString())
                        .putExtra(IntentKey.TRANSFER_URL, txHash));
    }


    @Override
    public void showGasPrice(BigInteger gasPrice) {
        realGas = gasPrice;

        FlyLog.i("gasPrice" + gasPrice);

        gaslimit = new BigDecimal(21000);
        String cost = mFormater.format(Convert.fromWei(gaslimit.multiply(new BigDecimal(realGas + "")), Convert.Unit.ETHER));

        tvGasCost.setText(String.valueOf(cost + "0" + mEtherUnit));
    }

    @Override
    public void showGasLimit(BigInteger gasLimit) {

    }

    @Override
    public void showRechargeResult(String txHash) {

    }


    @Override
    public void showTransferInfo() {
        mBottomSheet = new BottomSheetDialog(this);
        mBottomSheet.setCancelable(true);//设置点击外部是否可以取消
        mBottomSheet.setContentView(R.layout.layout_transferdetails);//设置对框框中的布局

        TextView address = mBottomSheet.findViewById(R.id.drawdetails_tv_address);
        TextView num = mBottomSheet.findViewById(R.id.drawdetails_tv_drawnum);
        TextView servicecharge = mBottomSheet.findViewById(R.id.drawdetails_tv_servicecharge);
        address.setText(mTransferAddress.getText());
        num.setText(String.valueOf(money + getString(R.string.etc_transfer_ether_unit)));
        servicecharge.setText(tvGasCost.getText());

        mBottomSheet.findViewById(R.id.iv_close).setOnClickListener(v -> mBottomSheet.dismiss());
        mBottomSheet.findViewById(R.id.drawdetails_btn_submit).setOnClickListener(v -> showCheckDialog());
        mBottomSheet.show();//显示弹窗
    }

    private void showCheckDialog() {
        inputPwdDialog.show();
        inputPwdDialog.setDeleteAlertVisibility(false);
        inputPwdDialog.setOnInputDialogButtonClickListener(this);
    }


    @Override
    protected void init() {
        StatusBarUtil.setToolBarPaddingTop(mToolbar, this);
        mToolbarTitle.setText(getString(R.string.excavate));
        mToolbarBack.setVisibility(View.VISIBLE);
        inputPwdDialog = new InputPwdDialog(this, R.style.inputAlert);
        loadingDialog = LoadingDialog.createLoadingDialog(this, getString(R.string.load), false);

        mReceiptAddress.setText(HttpConstants.ADMIN_ADDRESS);

        mEthWallet = getIntent().getParcelableExtra(IntentKey.ETH_WALLET);

        FlyLog.i("mEthWallet"+mEthWallet);

        mTransferAddress.setText(mEthWallet.getAddress());
        getPresenter().getCityBalance(mEthWallet.getAddress());
        getPresenter().getGasPrice();

        mPwd = mEthWallet.getPassword();

        mFormater = new DecimalFormat();
        //保留几位小数
        mFormater.setMaximumFractionDigits(8);
        //模式  四舍五入
        mFormater.setRoundingMode(RoundingMode.UP);
        mEtherUnit = getString(R.string.etc_transfer_ether_unit);
        tvGasCost.setText(String.valueOf(mFormater.format(miner_min) + "0" + mEtherUnit));
        seekbar.setOnSeekBarChangeListener(this);
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setAlignItems(AlignItems.STRETCH);

        mMCitys = new ArrayList<>();

        VerifyMnemonicWordTag city1 = new VerifyMnemonicWordTag();
        city1.setMnemonicWord("300");
        VerifyMnemonicWordTag city2 = new VerifyMnemonicWordTag();
        city2.setMnemonicWord("3000");
        VerifyMnemonicWordTag city3 = new VerifyMnemonicWordTag();
        city3.setMnemonicWord("30000");
        mMCitys.add(city1);
        mMCitys.add(city2);
        mMCitys.add(city3);

        ExcavateAdapter mAdapter = new ExcavateAdapter(R.layout.list_item_mnemoic, mMCitys);
        mRv.setLayoutManager(layoutManager);
        mRv.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {


            money = mMCitys.get(position).getMnemonicWord();
            for (int i = 0; i < mMCitys.size(); i++) {
                if (i == position) {
                    mMCitys.get(i).setSelected(true);
                } else {
                    mMCitys.get(i).setSelected(false);
                }
            }

            FlyLog.i("money" + money);
            mAdapter.notifyDataSetChanged();

        });

    }

    @Override
    protected int getContentView() {
        return R.layout.activity_excavate;
    }

    @OnClick({R.id.btn_next,R.id.toolbar_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_next:
                getPresenter().checkTransferInfo(mTransferAddress.getText().toString(), money, mBalance);

                break;
            case R.id.toolbar_back:
                onBackPressed();
                break;
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        String cost = null;
        if (progress == 0) {
            gaslimit = new BigDecimal(21000);
            cost = mFormater.format(Convert.fromWei(gaslimit.multiply(new BigDecimal(realGas + "")), Convert.Unit.ETHER));

        } else if (progress == 100) {
            gaslimit = new BigDecimal(210000);

            cost = mFormater.format(Convert.fromWei(gaslimit.multiply(new BigDecimal(realGas + "")), Convert.Unit.ETHER));
        } else {
            double p = progress / 100f;

            gaslimit = new BigDecimal(210000).multiply(new BigDecimal(p));

            cost = mFormater.format(Convert.fromWei(gaslimit.multiply(new BigDecimal(realGas + "")), Convert.Unit.ETHER));

        }
        tvGasCost.setText(String.valueOf(cost + "0" + mEtherUnit));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onConfirm(String pwd) {
        if (TextUtils.equals(mPwd, Md5Utils.md5(pwd))) {
            inputPwdDialog.dismiss();
            mBottomSheet.dismiss();
            getPresenter()
                    .transfer(pwd, "", mReceiptAddress.getText().toString(),
                            new BigInteger(money), new BigInteger(gaslimit.toString()), realGas);
        } else {
            ToastUtils.showToast(R.string.wallet_detail_wrong_pwd);
        }
    }
}
